<template>
<div class="demo">
    <!--通过自定义vite插件来获取展示Demo的标题-->
    <h2>{{component.__sourceCodeTitle}}</h2>
    <div class="demo-compoent">
        <!--通过component标签展示组件效果-->
        <component :is="component"></component>
    </div>
    <div class="demo-actions"><Button @click="toggleCode"><span><svg class="icon">
                    <use xlink:href="#icon-code1"></use>
                </svg></span>查看代码</Button></div>
    <div class="demo-code" v-if="codeVisible">
        <!--通过自定义vite插件来获取展示Demo的源码，源码封装在html中-->
        <pre class="language-html" v-html="html"></pre>
    </div>

</div>
</template>

<script lang="ts">
import {
    computed,
    ref
} from 'vue';
import 'prismjs';
import Button from '../lib/Button.vue'
import 'prismjs/themes/prism-okaidia.css'
//利用TS将window设为any类型，使得两边都是any类型
//可以让解释器运行Prism的任何实例对象（属性/方法）都不会报错
const Prism = (window as any).Prism;
export default {
    //需要导入的组件
    components: {
        Button
    },
    //从父组件获取组件作参数，类型是对象
    props: {
        component: Object,
    },
    //获取到父组件的传信内容，然后也可作参数传到setup中使用
    setup(props) {
        const codeVisible = ref(false);
        const toggleCode = () => {
            codeVisible.value = !codeVisible.value;
        }
        const html = computed(() => {
            //从prims.js官网查看调用方法，使得代码高亮，参数为源码以及高亮格式（以html的样式模板）
            return Prism.highlight(props.component.__sourceCode, Prism.languages.html, 'html')
        })
        return {
            html,
            codeVisible,
            toggleCode
        }
    }
}
</script>

<style lang="scss">
$border-color:#d9d9d9;

.demo {
    border: 1px solid $border-color;
    border-radius: 6px;
    margin: 20px 0 40px;

    >h2 {
        margin-bottom: 10px;
        padding: 10px 20px;
        border-bottom: 1px dashed $border-color;
    }

    &-compoent {
        padding: 0 20px;
    }

    // &-attention {
    //     padding: 10px 10px;
    // }

    &-actions {
        padding: 10px 10px;
        margin-top: 10px;
    }

    &-code {
        padding: 10px 10px;

        >pre {
            line-height: 1.1;
            font-family: Consolas, 'Courier New', Courier, monospace;
            margin: 0;
        }
    }
}

svg {
    //暂时硬性调整icon位置
    margin-right: 5px;
    width: 30px;
    height: 30px;
    transform: translateY(2.5px);
}
</style>
